<template>
  <div>
    <div class="" v-if="falg">
      <div class="basic">
        <div class="Useful">基本信息</div>
        <!-- 表单 -->
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm" label-position="rigth">
          <el-form-item label="套餐ID" class="formItem">
            <el-input :value="goodsPackageCode" maxlength="10" disabled>
            </el-input>
            <el-button style="background-color:#fd804c;color: #fff;" class="tag" @click="copy(goodsPackageCode)">复制ID</el-button>
          </el-form-item>
          <el-form-item label="套餐名称" prop="name" class="formItem">
            <el-input v-model="ruleForm.name" maxlength="10" placeholder="请输入套餐名称" show-word-limit>
            </el-input>
          </el-form-item>
          <el-form-item label="套餐描述" prop="describe" class="formItem">
            <el-input v-model="ruleForm.describe" maxlength="60" placeholder="请输入套餐描述" show-word-limit>
            </el-input>
          </el-form-item>
          <el-form-item label="套餐定制描述" prop="orderdescribe" class="formItem">
            <el-input v-model="ruleForm.orderdescribe" maxlength="20" placeholder="请输入套餐定制描述" show-word-limit>
            </el-input>
          </el-form-item>
          <el-form-item label="套餐标签" prop="tagname" class="formItem">
            <el-input v-model="ruleForm.tagname" placeholder="请输入套餐标签名称" maxlength="8" show-word-limit></el-input>
          </el-form-item>

          <el-form-item label="房屋面积配置" prop="doubleCodeList">
            <div v-for="(item, index) in ruleForm.doubleCodeList" :key="index" style="margin-bottom:5px;">
              <el-select v-model="ruleForm.doubleCodeList[index].areaScopeCode" placeholder="请选择房屋面积">
                <el-option v-for="item in housearealist" :key="item.areaScopeCode" :label="item.areaScopeName" :value="item.areaScopeCode">
                </el-option>
              </el-select>
              <el-select v-model="ruleForm.doubleCodeList[index].areaHouseCode" placeholder="请选择房屋户型" @visible-change="getHouseTypeList($event,index)">
                <el-option v-for="item in houseTypeVos" :key="item.areaHouseCode" :label="item.areaHouseName" :value="item.areaHouseCode">
                </el-option>
              </el-select>
              <el-button icon="el-icon-plus" style="background-color:#fd804c;color: #fff;" v-if="index === 0" @click="addgoodsregion"></el-button>
              <el-button icon="el-icon-minus" style="background-color:#fd804c;color: #fff;" v-if="index !== 0" @click="deletgoodsregion(index)"></el-button>
            </div>
          </el-form-item>
          <el-form-item label="套餐上下架" prop="resource">
            <el-radio-group v-model="ruleForm.resource">
              <el-radio :label="1">上架</el-radio>
              <el-radio :label="0">下架</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- <el-form-item label="推荐套餐选择" prop="goodsPkgCode">
            <div class="linput" v-for="(item, index) in ruleForm.goodsPkgCodeList" :key="index">
              <el-select v-model="ruleForm.goodsPkgCodeList[index].goodsPkgCode" placeholder="推荐套餐选择">
                <el-option
                  v-for="item in goodspkglist"
                  :key="item.goodsPkgCode"
                  :label="item.goodsPkgName"
                  :value="item.goodsPkgCode">
                </el-option>
              </el-select>
              <el-button icon="el-icon-plus"                   style="background-color:#fd804c;color: #fff;" v-if="index === 0" @click="addgoodsPkgCodeList" style="margin-left:10px;"></el-button>
              <el-button icon="el-icon-minus"                   style="background-color:#fd804c;color: #fff;" v-if="index !== 0" @click="deletegoodsPkgCodeList(index)" style="margin-left:10px;"></el-button>
            </div>
          </el-form-item> -->
          <el-form-item label="可售时段" prop="sellTimeIntervals">
            <!-- <div v-if="ruleForm.times==0">
              <el-time-select placeholder="起始时间" v-model="startTime" :picker-options="{start: '08:00',step: '00:30',end: '21:00'}">
              </el-time-select>
              <el-time-select placeholder="结束时间" v-model="endTime" @change="chooseTime" :picker-options="{start: '08:00',step: '00:30',end: '21:00',minTime: startTime}">
              </el-time-select>
            </div> -->
            <el-time-select v-model="sellTimeIntervals" format="HH:mm" @change="chooseTimeInterval" placeholder="选择可售时间点" :picker-options="{start: '08:00',step: '00:30',end: '21:00'}">
            </el-time-select>
            <!-- <el-radio-group v-model="ruleForm.times" style="margin-left:15px">
              <el-radio :label="1" @change="empty">整点形式</el-radio>
              <el-radio :label="0" @change="empty">时段形式</el-radio>
            </el-radio-group> -->
          </el-form-item>
          <el-form-item>
            <div>
              <el-tag v-for="(tag, i) in ruleForm.sellTimeIntervals" :key="i" closable type="success" @close="tagClose(tag)">
                {{ tag }}
              </el-tag>
            </div>
            <!-- <div v-if="ruleForm.times==0">
              <el-tag v-for="(tag, i) in ruleForm.sellTimeIntervals" :key="i" closable type="success" @close="tagClose(tag)">
                {{ tag }}
              </el-tag>
            </div> -->
          </el-form-item>
          <div class="buttons">
            <el-button style="background-color:#fd804c;color: #fff;" @click="submitForm('ruleForm')">下一步</el-button>
            <el-button style="background-color:#fd804c;color: #fff;" @click="save('ruleForm')">保存</el-button>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>
import Bus from "../../../api/bus";
import Clipboard from "clipboard";
import moment from "moment";
export default {
  props: {
    goodsPackageBase: {
      type: Object,
      required: true
    },
    goodsPackageRecommends: {
      type: Array,
      required: true
    }
  },
  data () {
    return {
      isloading: true,
      falg: true,
      region: '',
      startTime: '',
      endTime: '',
      ruleForm: {
        name: "",
        describe: "",
        orderdescribe: "",
        tagname: "",
        resource: 0,
        times: 1,
        areaHouseCode: '',
        doubleCodeList: [
          {
            areaScopeCode: "", // 房屋面积
            areaHouseCode: "", //房屋户型
          }
        ],
        goodsPkgCodeList: [
          {
            goodsPkgCode: "",
            goodsPkgName: ""
          }
        ],
        sellTimeIntervals: [] // 用户选择的可售时间列表
      },
      rules: {
        name: [
          { required: true, message: "请输入套餐名称", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur"
          }
        ],
        doubleCodeList: [
          { required: true, message: "请选择房屋面积配置", trigger: "change" }
        ],
        areaHouseCode: [
          { required: true, message: "请选择房屋户型配置", trigger: "change" }
        ],
        sellTimeIntervals: [
          { required: true, message: "请完整选择可售时间", trigger: "change" }
        ],
        resource: [
          { required: true, message: "请选择套餐上下架", trigger: "change" }
        ]
      },
      housearealist: [],
      goodspkglist: [],
      houseTypeVos: [], // 当前房屋户型枚举
      goodsPackageCode: "", // 套餐id
      sellTimeIntervals: "" // 当前选择的可售时间
    };
  },

  activated () {
    Bus.$on("falg", data => {
      this.falg = data;
    });
    this.GoodsPkgSelectedList();
  },
  created () {
    // url获取套餐id  不可更改
    const goodsPackageCode = this.$route.query.goodsPackageCode;
    this.goodsPackageCode = goodsPackageCode;
  },
  methods: {
    //清空
    empty () {
      this.tagClose()
      this.ruleForm.sellTimeIntervals = []
    },
    chooseTime () {
      this.ruleForm.sellTimeIntervals.push(this.startTime + '~' + this.endTime)
      this.startTime = "";
      this.endTime = "";
    },
    //添加房屋配置
    addgoodsregion () {
      this.houseTypeVos = []
      this.ruleForm.doubleCodeList.push({
        areaScopeCode: "",
        areaHouseCode: "",
      });
    },
    //删除房屋配置
    deletgoodsregion (index) {
      this.ruleForm.doubleCodeList.splice(index, 1);
    },
    submitForm (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // 添加推荐套餐的校验
          const flag = this.checkHasSamePackageCode();
          if (flag) return;
          // 可售时段为必填
          if (this.ruleForm.sellTimeIntervals.length == 0) {
            this.$message.error("可售时段为必填项");
            return false;
          }
          this.falg = false;
          Bus.$emit("falg2", true);
          this.save("ruleForm");
        } else {
          this.falg = true;
          return false;
        }
      });
    },
    getHouseAreaList () {
      // 房屋面积枚举
      this.$http({
        url: "/hsssystemadmin/houseAreaMapping/getHouseAreaList",
        method: "get"
      }).then(res => {
        const { data } = res;
        this.housearealist = data;
        // 获取户型枚举
        this.getHouseTypeList(true);
      });
    },
    GoodsPkgSelectedList () {
      // 推荐套餐枚举
      this.$http({
        url: "/hssgoodsadmin/serviceGoodsPkg/getServiceGoodsPkgSelectedList",
        method: "get"
      }).then(res => {
        const { data } = res;
        this.goodspkglist = data;
      });
    },
    addgoodsPkgCodeList () {
      // 增加推荐套餐item
      // 非空判断校验
      let flag = true;
      this.ruleForm.goodsPkgCodeList.forEach(item => {
        if (item.goodsPkgCode == "") {
          flag = false;
        }
      });
      if (!flag) {
        this.$message.error("请先填写完整");
        return false;
      }
      this.ruleForm.goodsPkgCodeList.push({
        goodsPkgCode: "",
        goodsPkgName: ""
      });
    },
    deletegoodsPkgCodeList (index) {
      // 删除推荐套餐item
      this.ruleForm.goodsPkgCodeList.splice(index, 1);
    },
    doublecode () {
      this.houseTypeVos = ''
    },
    getHouseTypeList (value, index) {
      this.ruleForm.doubleCodeList.forEach(e => {
        // this.region.push(e.areaScopeCode)
        this.region = e.areaScopeCode
        console.log(this.region)
      })
      let a = this.region
      console.log(a)
      if (value) {
        const findObj = this.housearealist.find(
          item => item.areaScopeCode === a
        );
        console.log(findObj)
        if (findObj != null) {
          this.houseTypeVos = findObj.houseTypeVos;
        } else {
          this.$message.error('请先选择房屋面积')
        }
      }
    },
    changeAreaScopeCode () {
      this.ruleForm.areaHouseCode = "";
    },
    copy (data) {
      let clipboard = new Clipboard(".tag", {
        text: function () {
          return data;
        }
      });
      clipboard.on("success", e => {
        this.$message({
          message: "复制成功",
          showClose: true,
          type: "success"
        });
        // 释放内存
        clipboard.destroy();
      });
    },
    async save (formName) {
      // 分布保存
      this.$refs[formName].validate(async valid => {
        if (valid) {
          // 添加推荐套餐的校验
          const flag = this.checkHasSamePackageCode();
          if (flag) return;
          // 可售时段为必填
          if (this.ruleForm.sellTimeIntervals.length == 0) {
            this.$message.error("可售时段为必填项");
            return false;
          }
          const goodsPackageRecommends = this.ruleForm.goodsPkgCodeList.map(
            item => {
              const obj = {};
              obj.goodsPackageRecommendCode = item.goodsPkgCode;
              return obj;
            }
          );
          const data = {
            goodsPackageCode: this.goodsPackageCode,
            goodsPackageBase: {
              goodsPackageName: this.ruleForm.name,
              goodsPackageDescription: this.ruleForm.describe,
              goodsPackageCustomizableDescription: this.ruleForm.orderdescribe,
              goodsPackageTag: this.ruleForm.tagname,
              doubleCodeList: this.ruleForm.doubleCodeList,
              // areaScopeCode: this.ruleForm.region,
              // areaHouseCode: this.ruleForm.areaHouseCode,
              isPutAway: this.ruleForm.resource,
              sellTimeIntervals: this.ruleForm.sellTimeIntervals
            },
            goodsPackageRecommends
          };
          const { success } = await this.$http({
            url: "/hssgoodsadmin/serviceGoodsPkg/updateGoodsPackageBase",
            method: "post",
            data
          });
          if (success === 1) {
            // 成功 父组件重新查询
            // this.$message.success('当前页面数据保存成功')
            this.$emit("research");
          }
        } else {
          this.$message.error("请填写完整必要参数");
        }
      });
    },
    checkHasSamePackageCode () {
      //校验推荐套餐
      const goodsPkgCodeList = [];
      this.ruleForm.goodsPkgCodeList.forEach(item => {
        if (goodsPkgCodeList.indexOf(item.goodsPkgCode) === -1) {
          goodsPkgCodeList.push(item.goodsPkgCode);
        }
      });
      // 拦截相同的套餐
      if (goodsPkgCodeList.length < this.ruleForm.goodsPkgCodeList.length) {
        this.$message.error("不能添加相同的推荐套餐");
        return true;
      }
      // 拦截选择的本套餐
      if (goodsPkgCodeList.indexOf(this.goodsPackageCode) != -1) {
        this.$message.error("不能添加本套餐为推荐套餐");
        return true;
      }
      return false;
    },
    chooseTimeInterval (t) {
      console.log(t)
      if (t !== null) {
        let time = t;
        if (this.ruleForm.sellTimeIntervals.indexOf(time) === -1) {
          this.ruleForm.sellTimeIntervals.push(time);
        }
      }
      this.sellTimeIntervals = "";
    },
    tagClose (tag) {
      // 删除所选的可售时段
      let tagList = this.ruleForm.sellTimeIntervals;
      tagList.splice(tagList.indexOf(tag), 1);
    }
  },
  watch: {
    goodsPackageBase (newvalue) {
      if (newvalue) {
        // 数据回显
        this.ruleForm = Object.assign({}, this.ruleForm, {
          name: this.goodsPackageBase.goodsPackageName,
          describe: this.goodsPackageBase.goodsPackageDescription,
          orderdescribe: this.goodsPackageBase
            .goodsPackageCustomizableDescription,
          tagname: this.goodsPackageBase.goodsPackageTag,
          doubleCodeList: this.goodsPackageBase.doubleCodeList,
          // region: this.goodsPackageBase.areaScopeCode,
          // areaHouseCode: this.goodsPackageBase.areaHouseCode,
          resource: this.goodsPackageBase.isPutAway,
          sellTimeIntervals: this.goodsPackageBase.sellTimeIntervals
        });
        this.getHouseAreaList();
      }
    },
    async goodsPackageRecommends (newvalue) {
      if (newvalue) {
        if (
          newvalue.length == 1 &&
          newvalue[0].goodsPackageRecommendCode == ""
        ) {
          return false;
        }
        const { data } = await this.$http({
          url: "/hssgoodsadmin/serviceGoodsPkg/getServiceGoodsPkgSelectedList",
          method: "get"
        });
        const newarr = [];
        newvalue.forEach(item => {
          const findObj = data.find(
            item1 => item1.goodsPkgCode === item.goodsPackageRecommendCode
          );
          newarr.push(findObj);
        });
        this.ruleForm.goodsPkgCodeList = newarr;
      }
    }
  }
};
</script>
<style scoped>
.basic {
  background-color: #fff;
  padding: 20px;
  box-sizing: border-box;
  position: relative;
}
.Useful {
  font-size: 18px;
  margin-bottom: 15px;
}
.checkDete {
  display: flex;
}
.checkDete .el-select {
  width: 120px;
  margin-right: 10px;
}
.linput {
  display: flex;
  margin-bottom: 5px;
}
.linputc {
  width: 150px;
  margin-left: 10px;
}
.buttons {
  text-align: center;
  position: absolute;
  bottom: -70px;
  left: 50%;
  transform: translateX(-50%);
}
.formItem {
  width: 500px;
}
</style>
<style lang="scss" scoped>
.formItem {
  /deep/ .el-form-item__content {
    display: flex;
    .el-button {
      margin-left: 10px;
    }
  }
}
.el-tag {
  margin-right: 10px;
}
</style>
